#include "mesh.h"
#include <gl/glew.h>
#include "mtxlib.h"

mesh_t::~mesh_t()
{
	if (vb)
		delete[] vb;
	if (ib)
		delete[] ib;
}

void mesh_t::draw()
{
	glBegin(GL_TRIANGLES);
	for (int i = 0; i < ci; ++i)
	{
		int vi = ib[i];
		glTexCoord2f(vb[vi].texcoord.x, vb[vi].texcoord.y);
		glNormal3f(vb[vi].norm.x, vb[vi].norm.y, vb[vi].norm.z);
		glVertex3f(vb[vi].pos.x, vb[vi].pos.y, vb[vi].pos.z);
	}
	glEnd();
}

void mesh_t::fromFile(const char *filename)
{
	FILE *fin = fopen(filename, "rt");
	fscanf(fin, "%d %d", &cv, &ci);
	vb = new vertex_t[cv];
	ib = new int[ci];
	for (int i = 0; i < cv; ++i)
		fscanf(fin, "%f %f %f %f %f %f %f %f", &vb[i].pos.x, &vb[i].pos.y, &vb[i].pos.z, &vb[i].norm.x, &vb[i].norm.y, &vb[i].norm.z, &vb[i].texcoord.x, &vb[i].texcoord.y);
	for (int i = 0; i < ci; ++i)
		fscanf(fin, "%d", &ib[i]);
	fclose(fin);
}
